#include "tick_timer_config.h"

#include "stm32f10x.h"
#include "stdio.h"

static uint8_t tick_timer_enable_flag = 0;
static uint8_t tick_timer_task_list_init_ok = 0;
static uint8_t tick_timer_pionter = 0;
static void (*tick_timer_task_list[TICK_TIMER_TOTAL])(void);

void tick_timer_enable(void)
{
//	printf("tick_timer_enable\r\n");
	tick_timer_enable_flag = 1;
}

void tick_timer_disable(void)
{
	tick_timer_enable_flag = 0;
}

void tick_timer_task_list_init(void)
{
	uint8_t i;
//	printf("tick_timer_task_list_init\r\n");
	for(i = 0; i < TICK_TIMER_TOTAL; i++) {
		tick_timer_task_list[i] = 0;
	}
	tick_timer_enable_flag = 0;
	tick_timer_pionter = TICK_TIMER_TOTAL;
	tick_timer_task_list_init_ok = 1;
}

uint8_t tick_timer_task_register(void (*tick_timer_task)(void), uint8_t tick_timer_task_num)
{
	uint8_t ret = 0;
//	printf("tick_timer_task_register: %d\r\n", tick_timer_task_num);
	if((tick_timer_task_num <= TICK_TIMER_TOTAL) &&
	   (tick_timer_task != 0)) {
		tick_timer_task_list[tick_timer_task_num] = tick_timer_task;
		ret = 1;
	}

	return ret;
}

static void tick_timer_pionter_run(void)
{
	if(tick_timer_enable_flag == 1){
		tick_timer_pionter++;
		if(tick_timer_pionter >= TICK_TIMER_TOTAL) {
			tick_timer_pionter = 0;
		}
//	printf("tick_timer_pionter_run -> %d\r\n", tick_timer_pionter);
	}
}

static void tick_timer_task_execution(void)
{
	if((tick_timer_enable_flag == 1)&&
		(tick_timer_task_list_init_ok == 1)) {

	  
//	  if(tick_timer_pionter == 0){
//		  GPIO_SetBits( GPIOB, GPIO_Pin_2 );	
//		}
//	  else if(tick_timer_pionter == 1){
//			  GPIO_ResetBits( GPIOB, GPIO_Pin_2 );  
//	  }
	  if(tick_timer_pionter == 3){
		  GPIO_SetBits( GPIOB, GPIO_Pin_2 );
	  }
	  else if(tick_timer_pionter == 4){
		  GPIO_ResetBits( GPIOB, GPIO_Pin_2 );
	  }

		if(tick_timer_task_list[tick_timer_pionter] != 0) {
			tick_timer_task_list[tick_timer_pionter]();
		}
	}
//	printf("tick_timer_task_execution @ %d\r\n", tick_timer_pionter);
}

void tick_timer_pionter_set(uint8_t tick_timer_pionter_num)
{
//	printf("tick_timer_pionter_set ->>>>> %d\r\n", tick_timer_pionter_num);

	tick_timer_timer_source_reset();
	tick_timer_pionter = tick_timer_pionter_num;
	tick_timer_task_execution();

}

void tick_timer_process(void)
{
//	printf("%d\r\n", tick_timer_pionter);
	tick_timer_pionter_run();
	tick_timer_task_execution();
}

